package com.karry.service.impl;

import com.karry.mapper.DianZanMapper;
import com.karry.pojo.DianZan;
import com.karry.service.DianZanService;
import com.karry.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.ArrayList;
import java.util.List;

public class DianZanServiceImpl implements DianZanService {

    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    @Override
    public ArrayList<DianZan> searchAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        DianZanMapper mapper = sqlSession.getMapper(DianZanMapper.class);

        List<DianZan> list = mapper.searchAllDianZan();
        sqlSession.close();
        return (ArrayList<DianZan>) list;
    }

    @Override
    public int searchBlogDianCount(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        DianZanMapper mapper = sqlSession.getMapper(DianZanMapper.class);

        int i = mapper.selectBlogDianZanCount(id);
        sqlSession.close();
        return i;
    }

    @Override
    public int searchUserDianBlogStatus(int blogId, int userId) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        DianZanMapper mapper = sqlSession.getMapper(DianZanMapper.class);

        int i = mapper.selectUserDianZanBlogStatus(blogId, userId);
        sqlSession.close();
        return i;
    }



    @Override
    public int dianZan(int blogId, int userId) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        DianZanMapper mapper = sqlSession.getMapper(DianZanMapper.class);

        //判断是否点赞过（不管现在的状态）
        int i = mapper.selectUserDianZanBlogRecordStatus(blogId, userId);
        if (i > 0){
            //点过
            int i1 = mapper.dianZanTwo(blogId, userId);
            sqlSession.close();
            return i1;
        }else {
            //没点过
            int i1 = mapper.dianZanOne(blogId, userId);
            sqlSession.close();
            return i1;
        }

    }

    @Override
    public int cancelDian(int blogId, int userId) {
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        DianZanMapper mapper = sqlSession.getMapper(DianZanMapper.class);

        //避免异常，先判断记录
        int i = mapper.selectUserDianZanBlogRecordStatus(blogId, userId);
        if (i > 0){
            int i1 = mapper.cancelDianZan(blogId, userId);
            sqlSession.close();
            return i1;
        }else {
            //没点过，异常情况
            sqlSession.close();
            return -1;
        }
    }
}
